// pages/reservation-info/reservation-info.js
const app = getApp()
import {
  shareOptions,
  chooseLocation
} from "../../utils/access"
import {
  getStorage,
  parse
} from "../../utils/utils"
import api from "../../config/api"
import request from "../../utils/request"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 回收类型：大件: bulky 家电: appliances 衣物: clothing 上门回收：recycle
    type: '',
    // 地址
    address: {},
    // 图片
    recycleImages: [],
    // 时间
    date: '',
    // 时间前半部分
    dateTime: '',
    // 时间后半部分
    dateHalf: '',
    // 物品总价
    sumPrice: '',
    // 选择物品数据
    categoryList: [],
    // 联系电话
    contactPhone: '',
    // 联系名字
    contact: '',
    isfocus: true,
    showDate: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const obj = parse(options.obj)
    console.log('options---', obj)
    this.setData({
      type: obj.type || '',
      sumPrice: obj.sumPrice || '',
      address: getStorage('addressInfo') || {},
      contact: getStorage('userInfo')?.nickName || '',
      contactPhone: getStorage('phone') || '',
      categoryList: obj.selectedList || [],
      isfocus: false,
    })
    if (obj.type === 'recycle') {
      let dateList = []
      dateList.push(this.getDateStr(0))
      dateList.push(this.getDateStr(1))
      dateList.push(this.getDateStr(2))
      this.setData({
        dateList
      })
    }
    this.getTargetCommunityInfo()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  // 获取目标小区信息
  async getTargetCommunityInfo() {
    const res = await request.get(api.targetCommunityInfo)
    if (res?.data) {
      const {
        provinceName,
        cityName,
        areaName,
        communityName,
        address,
        lat,
        lon,
      } = res.data
      this.setData({
        address: {
          province: provinceName || '',
          city: cityName || '',
          direct: areaName || '',
          region: (provinceName || '') + (cityName || '') + (areaName || ''),
          fromAddr: (communityName || '') + (address || ''),
          latitude: lat,
          longitude: lon,
        }
      })
    }
  },
  /**
   * 获取输入的值
   */
  handleChange(e) {
    const {
      address
    } = this.data;
    const {
      currentTarget = {}, detail = {}
    } = e;
    const {
      dataset: {
        key
      }
    } = currentTarget;
    this.setData({
      address: {
        ...address,
        [key]: detail.value
      },
      [key]: detail.value
    });
  },
  /**
   * 选择地址
   */
  handleSelectAddress() {
    chooseLocation((res) => {
      this.setData({
        address: res
      })
    }, this.data.address)
  },
  /**
   * 获取所选的日期
   */
  getSelectedDate(e) {
    const {
      date = ''
    } = e.detail;
    let dataStr = date.split(' ')
    this.setData({
      date,
      dateTime: dataStr[0],
      dateHalf: dataStr[1],
    });
  },


  // 预约回收展示 后三天时间组件
  handleChangeDate() {
    this.setData({
      showDate: true
    });
  },
  // 获取后几天日期
  getDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期  
    var y = dd.getFullYear();
    var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1); //获取当前月份的日期，不足10补0  
    var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate(); //获取当前几号，不足10补0  
    var day = ['今天', '明天', '后天'][AddDayCount]; //天数
    var week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六', ][dd.getDay()]; //周
    // 获取时间点
    let timingList = []
    let now = new Date()
    let date = y + "/" + m + "/" + d
    let time1 = new Date(date + ' ' + '8:30')
    let time2 = new Date(date + ' ' + '11:00')
    let time3 = new Date(date + ' ' + '13:00')
    let time4 = new Date(date + ' ' + '15:00')
    let time5 = new Date(date + ' ' + '16:30:00')
    if (now < time1) {
      timingList = ['08:30-11:00', '11:00-13:00', '13:00-15:00', '15:00-16:30', '16:30-18:00']
    } else if (now < time2) {
      timingList = ['11:00-13:00', '13:00-15:00', '15:00-16:30', '16:30-18:00']
    } else if (now < time3) {
      timingList = ['13:00-15:00', '15:00-16:30', '16:30-18:00']
    } else if (now < time4) {
      timingList = ['15:00-16:30', '16:30-18:00']
    } else if (now < time5) {
      timingList = ['16:30-18:00']
    }
    console.log(y + "-" + m + "-" + d)
    return {
      day,
      week,
      date: y + "-" + m + "-" + d,
      timingList
    }
  },
  changeDate(e) {
    const {
      date = ''
    } = e.detail;
    let dataStr = date.split(' ')
    this.setData({
      date,
      showDate: false,
      dateTime: dataStr[0],
      dateHalf: dataStr[1],
    });
  },
  dateClose() {
    this.setData({
      showDate: false
    });
  },

  // 图片是否在上传中
  getImageLoading(e) {
    this.imageLoading = e.detail
  },
  /**
   * 可回收物/大件图片
   */
  getRecycleImage(e) {
    const {
      list = []
    } = e.detail;
    this.setData({
      recycleImages: list
    });
  },
  /**
   * 提交预约单
   */
  handleSave() {
    const {
      address,
      date,
      recycleImages,
      contact,
      contactPhone
    } = this.data;
    if (JSON.stringify(address) === "{}") {
      wx.showToast({
        title: '请输入地址',
        icon: 'none'
      })
      return
    }
    if (!address.fromAddr || address.fromAddr.match(/^[ ]*$/)) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return
    }
    if (contact.match(/^[ ]*$/)) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }

    if (!(/^1[3456789]\d{9}$/.test(contactPhone))) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      })
      return
    }

    if (!date) {
      wx.showToast({
        title: '请选择时间',
        icon: 'none'
      })
      return
    }

    if (recycleImages && recycleImages.length === 0) {
      wx.showToast({
        title: '请上传回收物图片',
        icon: 'none'
      })
      return
    }
    if (this.imageLoading) {
      wx.showToast({
        title: '图片正在上传中',
        icon: 'none'
      })
      return
    }
    this.submitFormData(recycleImages);
  },

  /**
   * 提交数据
   */
  async submitFormData(list) {
    if (this.loading) return
    this.loading = true
    const {
      type,
      date,
      address,
      categoryList,
      contactPhone,
      contact,
      sumPrice
    } = this.data;
    let goodsList = []
    if(this.data.type === 'recycle'){
      goodsList = categoryList.map(item => {
        return {
          goodsId: item.id,
          goodsName: item.goodsName,
          quantity: item.value
        }
      })
    }else{
      goodsList = categoryList.map(item => {
        return {
          goodsName: item.goodsName,
          quantity: item.value
        }
      })
    }

    const params = {
      appointmentTime: date,
      province: address.province,
      city: address.city,
      area: address.direct,
      address: address.fromAddr,
      orderSubType: 1,
      orderType: type === 'recycle' ? 5 : type === 'bulky' ? 1 : type === 'appliances' ? 2 : 3,
      userName: contact,
      phone: contactPhone,
      picList: list,
      goodsList
    }
    // 大件传价格
    if (type === 'bulky') {
      params.price = sumPrice
    } else if (type === 'recycle') { //上门预约传总重
      params.weight = sumPrice
    }
    console.log('params---', params)
    let res = await request.post(api.submitOrder, params, {
      loading: true
    })
    if (res.httpStatus === 200) {
      wx.showToast({
        title: '预约成功',
        icon: 'none'
      })
      wx.redirectTo({
        url: `/pages/bookingSuccess/bookingSuccess`,
        complete: () => {
          this.loading = false
        }
      })
    } else {
      this.loading = false
    }

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    return shareOptions('default', e)
  },
})